package com.example.wangzh.developkit.utils;

import android.util.Log;

import com.example.wangzh.developkit.base.MyApplication;
import com.example.wangzh.developkit.utils.encrypt.AESUtil;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 简单的打印Log工具类
 */
@Deprecated
public class LogUtils {
    public static String TAG = "hce_cap_vcard";
    /**
     * 判断是否开启了Debug模式
     */
    public static boolean DEBUG = Log.isLoggable(TAG, Log.VERBOSE);
    /**
     *
     */
    public static boolean LOG_DEBUG = true;
    /**
     *
     */
    public static boolean LOG_TO_FILE = true;


    public static void setTag(String tag) {
        TAG = tag;
        DEBUG = Log.isLoggable(TAG, Log.VERBOSE);
    }

    public static void v(String tag, String message) {
        if (LOG_DEBUG) {
            Log.v(tag == null ? TAG : tag, buildMessage(message));
        }
    }

    public static void i(String tag, String message) {
        if (LOG_DEBUG) {
            Log.i(tag == null ? TAG : tag, buildMessage(message));
        }
        if (LOG_TO_FILE) {
            writeToFile(tag == null ? TAG : tag, buildMessage(message), "i");
        }
    }

    public static void d(String tag, String message) {
        if (LOG_DEBUG) {
            Log.d(tag == null ? TAG : tag, buildMessage(message));
        }
        if (LOG_TO_FILE) {
            writeToFile(tag == null ? TAG : tag, buildMessage(message), "d");
        }
    }

    public static void w(String tag, String message) {
        if (LOG_DEBUG) {
            Log.w(tag == null ? TAG : tag, buildMessage(message));
        }
        if (LOG_TO_FILE) {
            writeToFile(tag == null ? TAG : tag, buildMessage(message), "w");
        }
    }

    public static void e(String tag, String message) {
        if (LOG_DEBUG) {
            Log.e(tag == null ? TAG : tag, buildMessage(message));
        }
        if (LOG_TO_FILE) {
            writeToFile(tag == null ? TAG : tag, buildMessage(message), "e");
        }
    }

    /**
     * @return
     */
    private static String buildMessage(String message) {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        if (stackTraceElements == null || stackTraceElements.length < 1) {
            return message;
        }
        StackTraceElement stackTraceElement;
        if (stackTraceElements.length < 5) {
            stackTraceElement = stackTraceElements[stackTraceElements.length - 1];
        } else {
            stackTraceElement = stackTraceElements[4];
        }
        return String.format(Locale.US, "%s.%s(%s:%d) %s",
                stackTraceElement.getClassName().substring(stackTraceElement.getClassName().
                        lastIndexOf(".") + 1),
                stackTraceElement.getMethodName(),
                stackTraceElement.getFileName(),
                stackTraceElement.getLineNumber(),
                message);
    }

    public static void logThrowable(String tag, Throwable throwable) {
        LogUtils.e(tag, Log.getStackTraceString(throwable));
    }

    /**
     * 打印一个List的详情
     *
     * @param tag
     * @param message
     * @param list
     * @param <T>
     */
    public static <T> void logList(String tag, String message, List<T> list) {
        i(tag, "log list:" + message);
        if (list == null) {
            i(tag, "list is null");
            return;
        }
        if (list.size() == 0) {
            i(tag, "list is empty");
            return;
        }
        i(tag, "==========log list:" + list.getClass() + " start, size:" + list.size()
                + " ========== ");
        for (int i = 0; i < list.size(); i++) {
            String elementStr = "";
            try {
                elementStr = new Gson().toJson(list.get(i));
            } catch (Exception e) {
                e.printStackTrace();
                logThrowable(tag, e);
            }
            i(tag, i + ">>>" + elementStr);
        }
        i(tag, "==========log list:" + list.getClass() + " end=========");
    }

    public static <T> void logMap(String tag, String message, Map<String, T> map) {
        i(tag, "log map:" + message);
        if (map == null) {
            i(tag, "map is null");
            return;
        }
        if (map.size() == 0) {
            i(tag, "map is empty");
            return;
        }
        i(tag, "==========log map:" + map.getClass() + " start,size:" + map.size()
                + "==========");
        for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
            String key = iterator.next();
            String valueStr = "";
            try {
                valueStr = new Gson().toJson(map.get(key));
            } catch (Exception e) {
                e.printStackTrace();
                logThrowable(tag, e);
            }
            i(tag, "key>>>" + key + ">>>value>>>" + valueStr);
        }
        i(tag, "==========log map:" + map.getClass() + " end==========");
    }

    private static SimpleDateFormat sdf_DT_N = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    private static String dirPath = MyApplication.getInstance().getExternalCacheDir() + File.separator
            + MyApplication.getInstance().getPackageName() + File.separator + "log";

    private static ExecutorService threadPool = Executors.newFixedThreadPool(3);

    public static void clearOutDate() {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                File dir = new File(dirPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File[] files = dir.listFiles();
                if (files != null) {
                    for (File file : files) {
                        Date date;
                        try {
                            date = sdf_DT_N.parse(file.getName());
                        } catch (ParseException e) {
                            date = new Date(0);
                            e.printStackTrace();
                        }
                        //超过七天的删除掉
                        if (System.currentTimeMillis() - date.getTime() > 3600 * 24 * 7) {
                            file.delete();
                        }
                    }
                }
            }
        });
    }

    public static void writeToFile(final String tag, final String msg, final String level) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                File dir = new File(dirPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File[] files = dir.listFiles();
                File outputFile;
                if (files == null || files.length == 0) {
                    outputFile = new File(dirPath + File.separator +
                            sdf_DT_N.format(new Date()) + ".log");
                } else if (files[files.length - 1].length() > 1 * 1024 * 1024) {
                    outputFile = new File(dirPath + File.separator +
                            sdf_DT_N.format(new Date()) + ".log");
                } else {
                    outputFile = files[files.length - 1];
                }
                StringBuffer sb = new StringBuffer().append(sdf_DT_N.format(new Date())).append(">>>")
                        .append(level).append(">>>")
                        .append(tag).append(">>>")
                        .append(msg).append("\r\n");
                try {
                    FileOutputStream fos = new FileOutputStream(outputFile, true);
                    fos.write(sb.toString().getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

